import json

from PyQt6.QtWidgets import *
from httpApi.httpApi import HttpApi
from ui_py.devicelistUI import Ui_devicelistwidget,showUpdateRS485DeviceDialog


class DeviceListController(QWidget, Ui_devicelistwidget):

    def __init__(self, mapData):
        super(DeviceListController, self).__init__()
        self.setupUi(self)
        self.retranslateUi(self)
        self.mapData = mapData
        self.listData = []
        self.zigbeeMap = {}
        self.zigbeeList = []
        self.rs485Map = {}
        self.rs485List = []
        self.rs485headers = ["设备名称", "设备地址", "所属服务器", "端口号", "设备型号配置", "通信协议"]
        # 设置布局
        self.verticalLayout_2.addWidget(self.tableWidget)
        self.addButton = QPushButton("+", self)
        self.verticalLayout_2.addWidget(self.addButton)
        self.addButton.clicked.connect(self.showUpdateRS485DeviceDialog)
        self.savedaviceButton = QPushButton("保存", self)
        self.verticalLayout_2.addWidget(self.savedaviceButton)
        self.savedaviceButton.clicked.connect(self.savedevices)
        

        self.creatInit()
        self.creatData()
    def create_func_butten2RS485(self):
        # 添加一个导入添加设备按钮
        self.addButton = QPushButton("+", self)
        self.verticalLayout_2.addWidget(self.addButton)
        self.addButton.clicked.connect(self.showUpdateRS485DeviceDialog)
        
    def creatInit(self):
        self.zigbeebutton.clicked.connect(self.zigbeeClick)
        self.rs485button.clicked.connect(self.rs485Click)
        #将加号按钮连接到槽函数
        # self.addButton.clicked.connect(self.addDevice)
        pass

    def zigbeeClick(self):
        self.tableWidget.clear()
        self.tableWidget.setRowCount(len(self.zigbeeList))
        for i in range(len(self.zigbeeList)):
            self.tableWidget.setHorizontalHeaderItem(0, QTableWidgetItem("设备名称"))
            self.tableWidget.setHorizontalHeaderItem(1, QTableWidgetItem("设备分类"))
            self.tableWidget.setHorizontalHeaderItem(2, QTableWidgetItem("设备配置"))
            self.tableWidget.setHorizontalHeaderItem(3, QTableWidgetItem("通讯协议"))
            self.tableWidget.setHorizontalHeaderItem(4, QTableWidgetItem("备注"))

            self.tableWidget.setItem(i, 0, QTableWidgetItem(self.zigbeeList[i]["name"]))
            self.tableWidget.setItem(i, 1, QTableWidgetItem(self.zigbeeList[i]["type"]))
            self.tableWidget.setItem(i, 2, QTableWidgetItem(self.zigbeeList[i]["label"]))
            self.tableWidget.setItem(i, 3, QTableWidgetItem(self.zigbeeList[i]["protocol"]))
            self.tableWidget.setItem(i, 4, QTableWidgetItem(self.zigbeeList[i]["notes"]))
            # 设置单元格自动换行
            self.tableWidget.setWordWrap(True)
            # 设置自适应宽度
            self.tableWidget.resizeColumnsToContents()


    def rs485Click(self):
        self.tableWidget.clear()
        # 设置表格数据
        self.tableWidget.setRowCount(len(self.rs485List))
        for col, header_text in enumerate(self.rs485headers):
                header_item = QTableWidgetItem(header_text)
                self.tableWidget.setHorizontalHeaderItem(col, header_item)
        # 设置表头
        for i in range(len(self.rs485List)):
            self.tableWidget.setItem(i, 0, QTableWidgetItem(self.rs485List[i]["name"]))
            self.tableWidget.setItem(i, 1, QTableWidgetItem(self.rs485List[i]["addr"]))
            self.tableWidget.setItem(i, 2, QTableWidgetItem(self.rs485List[i]["host"]))
            self.tableWidget.setItem(i, 3, QTableWidgetItem(self.rs485List[i]["port"]))
            self.tableWidget.setItem(i, 4, QTableWidgetItem(self.rs485List[i]["ttype"]))
            self.tableWidget.setItem(i, 5, QTableWidgetItem(self.rs485List[i]["notes"]))

        # 设置单元格自动换行
        self.tableWidget.setWordWrap(True)
        # 设置自适应宽度
        self.tableWidget.resizeColumnsToContents()

    def addNewRow(self, row):
        # 添加新行
        current_row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(current_row)

        # 在新行中添加数据，可以根据需要设置默认值
        # self.rs485headers = ["设备名称", "设备地址", "所属服务器", "端口号", "设备型号配置", "通信协议"]
        default_values = ["", "", "", "", "", ""]
        default_values[0] = row["device_name"]
        default_values[1] = row["device_category"]
        default_values[2] = row["device_name"]
        default_values[3] = row["device_name"]
        default_values[4] = row["device_configuration"]
        default_values[5] = row["device_name"]
        for col, value in enumerate(default_values):
            item = QTableWidgetItem(value)
            self.tableWidget.setItem(current_row, col, item)


    def creatData(self):
        HttpApi().requestGet(
            url=f"http://om.jujiembs.com/api/plugins/telemetry/DEVICE/{self.mapData['id']['id']}/values/attributes",
            callback=lambda value: {
                self.updateData(value)
            })

    def updateData(self, listData):
        self.listData = listData
        for item in self.listData:
            if item["key"] == "zigbee2mqtt_config":
                self.zigbeeMap = item
            if item["key"] == "rs485tomqtt_config":
                self.rs485Map = item

        if self.zigbeeMap["value"] != "none":
            self.handleZigbee()
        if self.rs485Map["value"] != 'none':
            self.handleRs485()

    def handleZigbee(self):
        #print(self.zigbeeMap)
        if "devices" not in self.zigbeeMap["value"]:
            return
        deviceMap: dict = self.zigbeeMap["value"]["devices"]
        for item in deviceMap.values():
            originalName: str = item["friendly_name"]
            type = originalName.split("/")[0]
            if type == "单路开关":
                name: str = originalName.split("%1[")[1]
                name = name.split("]1%")[0]
                self.zigbeeList.append(
                    {"name": name, "type": "照明设备", "label": "用能设备", "protocol": "zigbee", "notes": type})
            elif type == "双路开关":
                firstdevicename: str = originalName.split("%1[")[1]
                firstdevicename = firstdevicename.split("]1%")[0]
                self.zigbeeList.append(
                    {"name": firstdevicename, "type": "照明设备", "label": "用能设备", "protocol": "zigbee",
                     "notes": type})
                twoname: str = originalName.split("%2[")[1]
                twoname = twoname.split("]2%")[0]
                self.zigbeeList.append(
                    {"name": twoname, "type": "照明设备", "label": "用能设备", "protocol": "zigbee", "notes": type})
            elif type == "三路开关":
                firstdevicename: str = originalName.split("%1[")[1]
                firstdevicename = firstdevicename.split("]1%")[0]
                self.zigbeeList.append(
                    {"name": firstdevicename, "type": "照明设备", "label": "用能设备", "protocol": "zigbee",
                     "notes": type})
                twoname: str = originalName.split("%2[")[1]
                twoname = twoname.split("]2%")[0]
                self.zigbeeList.append(
                    {"name": twoname, "type": "照明设备", "label": "用能设备", "protocol": "zigbee", "notes": type})
                threename: str = originalName.split("%3[")[1]
                threename = threename.split("]3%")[0]
                self.zigbeeList.append(
                    {"name": threename, "type": "照明设备", "label": "用能设备", "protocol": "zigbee", "notes": type})
            else:
                if "/" not in originalName:
                    self.zigbeeList.append(
                        {"name": originalName, "type": "未知", "label": "未知", "protocol": "未知", "notes": "未知"})
                    pass
                else:
                    name: str = originalName.split("/")[1]
                    type = originalName.split("/")[0]
                    label = ""
                    if "传感器" in name:
                        label = "传感器"
                    self.zigbeeList.append(
                        {"name": name, "type": type, "label": label, "protocol": "zigbee", "notes": type})

    def handleRs485(self):
        # print(self.rs485Map)
        map: dict = self.rs485Map["value"]["rs485"]
        if "modbus_slaves" in map.keys():
            modbuslist: list = map["modbus_slaves"]
            for i in range(len(modbuslist)):
                devicelist = modbuslist[i]["devices"]
                for j in range(len(devicelist)):
                    self.rs485List.append(
                        {"name": devicelist[j]["name"], "addr": str(devicelist[j]["addr"]),
                         "ttype": devicelist[j]["type"],
                         "host": modbuslist[i]["host"],
                         "port": str(modbuslist[i]["port"]),
                         "notes": "modbus协议"})
                    
        if "proto_645" in map.keys():
            proto645list: list = map["proto_645"]
            for i in range(len(proto645list)):
                devicelist = proto645list[i]["devices"]
                for j in range(len(devicelist)):
                    self.rs485List.append(
                        {"name": devicelist[j]["name"], "addr": str(devicelist[j]["addr"]),
                         "ttype": devicelist[j]["type"],
                         "host": proto645list[i]["host"],
                         "port": str(proto645list[i]["port"]),
                         "notes": f"{proto645list[i]['version']}协议"})
                    
    def handleItemChanged(self, type,item):
        row = item.row()
        col = item.column()
        new_value = item.text()
        if type == "rs485List":
            # 检查行索引是否在有效范围内
            if 0 <= row < len(self.rs485List):
                # 可以安全地访问列表
                new_value = item.text()
                # 在这里根据行和列的不同，更新对应的参数
                if col == 0:  # 设备名称
                    self.rs485List[row]["name"] = new_value
                elif col == 1:  # 设备地址
                    self.rs485List[row]["addr"] = new_value
                elif col == 2:  # 所属服务器
                    self.rs485List[row]["host"] = new_value
                elif col == 3:  # 端口号
                    self.rs485List[row]["port"] = new_value
                elif col == 4:  # 设备型号配置
                    self.rs485List[row]["ttype"] = new_value
                elif col == 5:  # 备注
                    self.rs485List[row]["notes"] = new_value
        else:
            pass

        # 打印更新后的 rs485List，调试时使用
        # print(self.rs485List)

    def addDevice_toRs485(self):
        #添加设备顺序
        #设备类型--->串口服务器地址--->端口号--->设备id--->设备配置文件--->
        pass
    def addDevice(self):
        # 处理添加新设备的逻辑
        # 可以打开一个对话框来获取用户输入的设备详情
        # 更新数据结构并刷新 UI
        pass

    def showUpdateRS485DeviceDialog(self):
        # 创建并显示新的对话框
        update_device_dialog = showUpdateRS485DeviceDialog()
        result = update_device_dialog.exec()  #Use exec() to show the dialog in a blocking way
        # 处理对话框的返回结果，如果需要的话
        if result == QDialog.DialogCode.Accepted:
            self.addNewRow(update_device_dialog.updatadic)
            
            print(update_device_dialog.updatadic)
            print("设备更新成功")
        else:
            print("设备更新取消")
    def savedevices(self):
        pass